package backend;

import java.sql.SQLException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import logs.LogFactory;

import org.apache.log4j.Logger;

import backend.db.ConnectionManager;

public class ConnectionPool {
  private static final Logger logger = LogFactory.getLog(ConnectionPool.class);
  public static int MAX_CONNECTIONS = 6;
  public static BlockingQueue<ConnectionManager> availableConnections;
  
  public static void initConnectionPool(final String url, final String username, final String password)
      throws SQLException {
    logger.debug("initConnectionPool");
    availableConnections = new ArrayBlockingQueue<ConnectionManager>(MAX_CONNECTIONS);
    ConnectionManager cm;
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
      cm = new ConnectionManager(url, username, password);
      cm.connect();
      availableConnections.add(cm);
    }
  }
  
  public void releaseConnection(final ConnectionManager cm) {
    logger.debug("releaseConnection");
    availableConnections.add(cm);
  }
  
  public ConnectionManager captureConnection() {
    logger.debug("captureConnection");
    while (true)
      try {
        return availableConnections.take();
      } catch (final InterruptedException e) {
        // just try again
      }
  }
  
  public static void destroyPool() {
    logger.debug("destroyPool");
    while (!availableConnections.isEmpty()) {
      final ConnectionManager cm = availableConnections.remove();
      cm.disconnect();
    }
  }
}
